package com.gitee.wsl.data.store

import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

class StateSavedVar<T : Any>(
    val state: StoreServer,
    val key:String,
    val defaultValue:T,
    saveDefault:Boolean = false,
): ReadWriteProperty<Any, T> {

    //var init = false
    //private var _value = state.getPreferenceOrDefault(key,defaultValue)

    init {
        if(saveDefault && state.isNotExits(key)){
            state.put(key,defaultValue)
        }
//        if(flowAble) {
//            //initValue()
//            scope.launch {
//                if(!ApplicationConfig.eventBus.isExits(key))
//                    ApplicationConfig.eventBus.publish(key,_value)
//            }
//
//        }
    }

    override fun getValue(thisRef: Any, property: KProperty<*>): T {
        return state.getOrDefault(key,defaultValue)
    }

    override fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
        state.put(key,value)
    }
}

fun <T : Any> saveAble(state: StoreServer, key:String, defaultValue:T, saveDefault:Boolean=false) = StateSavedVar(state,key, defaultValue,saveDefault)

fun <T : Any> saveAble(state: StoreServer, key:String, saveDefault:Boolean=false, defaultValueBlock:()->T) = StateSavedVar(state,key, defaultValueBlock(),saveDefault)
